<template>
  <!-- 辅导师维度开业辅导统计 -->
  <el-card class="data-card" shadow="never">
    <div slot="header" class="card-header">
      <div class="header-left">
        <i class="el-icon-user-solid" />
        <span>辅导师维度统计（开业辅导）</span>
      </div>
      <div class="header-right">
        <!-- 品牌选择器 -->
        <el-select v-model="filterForm.brand" placeholder="请选择品牌" size="small" style="width: 140px; margin-right: 8px;" @change="handleFilterChange">
          <el-option label="全部" value="" />
          <el-option v-for="item in brandOptions" :key="item.enCode" :label="item.fullName" :value="item.enCode" />
        </el-select>

        <!-- 管理区域选择器 -->
        <el-select v-model="filterForm.managementArea" placeholder="请选择管理区域" size="small" style="width: 160px; margin-right: 8px;" @change="handleFilterChange">
          <el-option label="全部" value="" />
          <el-option v-for="item in localManagementAreaOptions" :key="item.enCode" :label="item.fullName" :value="item.enCode" />
        </el-select>

        <!-- 时间范围选择器（yyyy-MM-dd） -->
        <el-date-picker v-model="filterForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" size="small" style="width: 260px; margin-right: 8px;" @change="handleFilterChange" />

        <el-button size="small" icon="el-icon-refresh" :loading="loading" @click="refreshData">刷新</el-button>
      </div>
    </div>

    <div v-loading="loading" class="table-container">
      <!-- 空状态 -->
      <el-empty v-if="!tableData || tableData.length === 0" description="暂无数据" />

      <!-- 动态表格：辅导师 × 品牌列 + 汇总列 -->
      <el-table v-else :data="tableData" size="small" stripe border class="report-table optimized-table" :summary-method="getTableSummaries" show-summary sum-text="总计" height="auto">
        <el-table-column type="index" width="55" align="center" />
        <!-- 行头：辅导师姓名 -->
        <el-table-column prop="instructorName" label="辅导师" min-width="80" align="center" />
        <!-- 汇总列：总开业｜总达标｜总达标率｜总及格｜总及格率 -->
        <el-table-column label="汇总" min-width="220" align="center">
          <template #default="scope">
            <div class="cell-3">
              <div class="metric-line">
                <span>开业：</span>
                <span class="num">{{ scope.row.totalOpenCount }}</span>
                <span class="sep">｜</span>
                <span>达标：</span>
                <span class="num">{{ scope.row.totalQualifiedCount }}</span>
                <span class="sep">｜</span>
                <span>及格：</span>
                <span class="num">{{ scope.row.totalPassCount || 0 }}</span>
              </div>
              <div class="metric-line">
                <span>达标率：</span>
                <span class="num" style="color: #409EFF;">{{ formatRate(scope.row.totalQualifiedRate) }}%</span>
                <span class="sep">｜</span>
                <span>及格率：</span>
                <span class="num">{{ formatRate(scope.row.totalPassRate || 0) }}%</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <!-- 动态品牌列：每列显示 开业数｜达标数｜达标率｜及格数｜及格率 -->
        <el-table-column v-for="brand in brands" :key="brand" :label="getBrandName(brand)" :column-key="brand" align="center" min-width="220">
          <template #default="scope">
            <div class="cell-3">
              <div class="metric-line">
                <span>开业：</span>
                <span class="num">{{ getBrandMetric(scope.row, brand, 'openCount') }}</span>
                <span class="sep">｜</span>
                <span>达标：</span>
                <span class="num">{{ getBrandMetric(scope.row, brand, 'qualifiedCount') }}</span>
                <span class="sep">｜</span>
                <span>及格：</span>
                <span class="num">{{ getBrandMetric(scope.row, brand, 'passCount') }}</span>
              </div>
              <div class="metric-line">
                <span>达标率：</span>
                <span class="num" style="color: #409EFF;">{{ formatRate(getBrandMetric(scope.row, brand, 'qualifiedRate')) }}%</span>
                <span class="sep">｜</span>
                <span>及格率：</span>
                <span class="num">{{ formatRate(getBrandMetric(scope.row, brand, 'passRate')) }}%</span>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-card>
</template>

<script>
// 引入报表服务 API
import { getTeacherGuidanceStatistics } from '@/api/report/services'
import { DICTIONARY_TYPES, getEnabledDictionaryData } from '@/utils/dictionaryConstants'

export default {
  name: 'TeacherGuidanceStatisticsReport',

  props: {
    // 来自父级的管理区域字典选项（可选）
    managementAreaOptions: {
      type: Array,
      default: () => []
    }
  },

  data() {
    const currentYear = new Date().getFullYear()
    const startDate = `${currentYear}-01-01`
    const endDate = `${currentYear}-12-31`

    return {
      loading: false,
      brands: [],
      tableData: [],

      // 本组件独立维护的品牌字典（用于下拉选项）
      brandOptions: [],

      // 本组件使用的管理区域选项（避免修改父级 prop）
      localManagementAreaOptions: [],

      // 筛选表单
      filterForm: {
        brand: '',
        managementArea: '',
        dateRange: [startDate, endDate]
      }
    }
  },

  mounted() {
    // 加载字典并初始化数据
    this.initDictionaries().then(() => this.loadData())
  },

  watch: {
    /**
     * 同步父组件传入的管理区域选项到本地副本
     * 避免直接修改 prop，遵循单向数据流
     * @param {Array} newVal 新的管理区域选项
     */
    managementAreaOptions: {
      immediate: true,
      handler(newVal) {
        this.localManagementAreaOptions = Array.isArray(newVal) ? newVal : []
      }
    }
  },

  methods: {
    /**
     * 初始化字典（品牌、管理区域）
     * - 保留与项目一致的字典加载方式
     */
    async initDictionaries() {
      try {
        // 如果父组件未传管理区域字典，则自行加载启用项
        if (!this.managementAreaOptions || this.managementAreaOptions.length === 0) {
          this.$emit('loading', true)
          const areas = await getEnabledDictionaryData(DICTIONARY_TYPES.COMPANY)
          this.$emit('loading', false)
          this.$emit('filter-options-loaded', { areas })
          // 更新本地副本，避免直接修改 prop
          this.localManagementAreaOptions = Array.isArray(areas) ? areas : []
        }
      } catch (error) {
        this.$message.error('管理区域选项加载失败')
      }

      try {
        const brands = await getEnabledDictionaryData(DICTIONARY_TYPES.BRAND)
        this.brandOptions = brands || []
      } catch (error) {
        this.brandOptions = []
        this.$message.error('品牌选项加载失败')
      }
    },

    /**
     * 获取查询参数
     * @returns {Object} 查询参数对象（camelCase）
     */
    getQueryParams() {
      const params = {}
      // 品牌筛选
      if (this.filterForm.brand) params.brand = this.filterForm.brand
      // 管理区域筛选
      if (this.filterForm.managementArea) params.managementArea = this.filterForm.managementArea
      // 时间范围
      if (this.filterForm.dateRange && this.filterForm.dateRange.length === 2) {
        params.startDate = this.filterForm.dateRange[0]
        params.endDate = this.filterForm.dateRange[1]
      }
      return params
    },

    /**
     * 加载辅导师维度统计数据
     * 流程：
     * 1) 构造查询参数（品牌/管理区域/时间范围），与后端接口一致
     * 2) 调用接口获取 { brands, table } 数据结构
     * 3) 更新表格展示状态；无数据时显示空状态
     */
    async loadData() {
      if (this.loading) return
      this.loading = true
      this.$emit('loading', true)
      try {
        const params = this.getQueryParams()
        const resp = await getTeacherGuidanceStatistics(params)
        // 兼容不支持可选链的编译环境：优先取 resp.data，其次取 resp，最后回退为空对象
        const payload = (resp && resp.data) || resp || {}

        this.brands = Array.isArray(payload.brands) ? payload.brands : []
        this.tableData = Array.isArray(payload.table) ? payload.table : []

        // 数据加载完成后：按行的“总达标率”进行倒序排序（高→低）
        // 说明：优先使用 row.totalQualifiedRate；若缺失则按（总达标数/总开业数*100）计算；再不然按品牌汇总加权计算
        this.tableData = this.tableData.slice().sort((a, b) => {
          const rateA = this.getRowTotalQualifiedRate(a)
          const rateB = this.getRowTotalQualifiedRate(b)
          return rateB - rateA
        })

        // 通知父组件数据已更新
        this.$emit('data-updated', {
          brands: this.brands,
          table: this.tableData
        })
        // 合并汇总行前两列（视觉合并）
        this.mergeFooterCells()
      } catch (error) {
        this.$message.error('辅导师统计数据加载失败')
        console.error('TeacherGuidanceStatisticsReport load error:', error)
        // 回退空数据
        this.brands = []
        this.tableData = []
      } finally {
        this.loading = false
        this.$emit('loading', false)
      }
    },
    /**
     * 合并表格底部汇总行前两列（视觉）：隐藏第一列并将第二列设置 colspan=2
     */
    mergeFooterCells() {
      this.$nextTick(() => {
        try {
          const footerRow = this.$el.querySelector('.el-table__footer-wrapper table tbody tr') || this.$el.querySelector('.el-table__footer-wrapper tr')
          if (!footerRow) return
          const tds = footerRow.querySelectorAll('td')
          if (tds && tds.length >= 2) {
            const first = tds[0]
            const second = tds[1]
            first && (first.style.display = 'none')
            second && second.setAttribute('colspan', '2')
          }
          // 替换“汇总”列的单元格内容为与内容行一致的样式结构
          const headerRow = this.$el.querySelector('.el-table__header-wrapper table thead tr')
          if (!headerRow) return
          const ths = headerRow.querySelectorAll('th')
          let summaryIndex = -1
          const headerTextIndexMap = {}
          ths.forEach((th, idx) => {
            const txt = (th.textContent || '').trim()
            headerTextIndexMap[txt] = idx
            if (txt === '汇总') summaryIndex = idx
          })
          if (summaryIndex >= 0 && tds[summaryIndex]) {
            const cell = tds[summaryIndex].querySelector('.cell') || tds[summaryIndex]
            const html = this.buildSummaryHtml()
            if (cell) cell.innerHTML = html
          }
          // 品牌列总计：逐品牌替换为内容样式结构
          if (Array.isArray(this.brands) && this.brands.length > 0) {
            this.brands.forEach(brand => {
              const label = this.getBrandName(brand)
              const idx = headerTextIndexMap[label]
              if (typeof idx === 'number' && idx >= 0 && tds[idx]) {
                const cell = tds[idx].querySelector('.cell') || tds[idx]
                const html = this.buildBrandSummaryHtml(brand)
                if (cell) cell.innerHTML = html
              }
            })
          }
        } catch (_) {}
      })
    },
    /**
     * 构建汇总行HTML，样式与内容行保持一致（两行展示、数值加粗蓝色）
     */
    buildSummaryHtml() {
      const totalOpen = this.tableData.reduce((acc, row) => acc + Number(row.totalOpenCount || 0), 0)
      const totalQualified = this.tableData.reduce((acc, row) => acc + Number(row.totalQualifiedCount || 0), 0)
      const totalPass = this.tableData.reduce((acc, row) => acc + Number(row.totalPassCount || 0), 0)
      const rate = totalOpen === 0 ? 0 : (totalQualified / totalOpen) * 100
      const passRate = totalOpen === 0 ? 0 : (totalPass / totalOpen) * 100
      return `<div class="cell-3">` + `<div class="metric-line">` + `<span>开业：</span><span class="num">${totalOpen}</span>` + `<span class="sep">｜</span>` + `<span>达标：</span><span class="num">${totalQualified}</span>` + `<span class="sep">｜</span>` + `<span>及格：</span><span class="num">${totalPass}</span>` + `</div>` + `<div class="metric-line">` + `<span>达标率：</span><span class="num" style="color:#409EFF;">${this.formatRate(rate)}%</span>` + `<span class="sep">｜</span>` + `<span>及格率：</span><span class="num">${this.formatRate(passRate)}%</span>` + `</div>` + `</div>`
    },

    /**
     * 构建品牌列总计HTML，样式与内容行保持一致（两行展示、数值加粗蓝色）
     * @param {string} brand 品牌编码或名称
     */
    buildBrandSummaryHtml(brand) {
      const openSum = this.tableData.reduce((acc, row) => acc + Number(this.getBrandMetric(row, brand, 'openCount') || 0), 0)
      const qualifiedSum = this.tableData.reduce((acc, row) => acc + Number(this.getBrandMetric(row, brand, 'qualifiedCount') || 0), 0)
      const passSum = this.tableData.reduce((acc, row) => acc + Number(this.getBrandMetric(row, brand, 'passCount') || 0), 0)
      const rate = openSum === 0 ? 0 : (qualifiedSum / openSum) * 100
      const passRate = openSum === 0 ? 0 : (passSum / openSum) * 100
      return `<div class="cell-3">` + `<div class="metric-line">` + `<span>开业：</span><span class="num">${openSum}</span>` + `<span class="sep">｜</span>` + `<span>达标：</span><span class="num">${qualifiedSum}</span>` + `<span class="sep">｜</span>` + `<span>及格：</span><span class="num">${passSum}</span>` + `</div>` + `<div class="metric-line">` + `<span>达标率：</span><span class="num" style="color:#409EFF;">${this.formatRate(rate)}%</span>` + `<span class="sep">｜</span>` + `<span>及格率：</span><span class="num">${this.formatRate(passRate)}%</span>` + `</div>` + `</div>`
    },

    /**
     * 处理筛选条件变化
     */
    handleFilterChange() {
      this.loadData()
      this.$emit('filter-change', this.filterForm)
    },

    /**
     * 刷新数据（保持筛选条件）
     */
    refreshData() {
      this.loadData()
      this.$emit('refresh')
    },

    /**
     * 获取品牌单元格的指标值
     * @param {Object} row 行数据（TeacherGuidanceStatisticsRow）
     * @param {string} brand 品牌名称
     * @param {('openCount'|'qualifiedCount'|'qualifiedRate')} field 指标字段
     * @returns {number} 指标数值（缺失时返回0）
     */
    getBrandMetric(row, brand, field) {
      if (!row || !Array.isArray(row.brandData)) return 0
      const cell = row.brandData.find(x => x.brand === brand)
      if (!cell) return 0
      const value = cell[field]
      if (typeof value === 'number') return value
      const num = Number(value)
      return isNaN(num) ? 0 : num
    },

    /**
     * 格式化百分比（保留两位小数）
     * @param {number} rate 百分比数值
     * @returns {string} 格式化后的百分比字符串
     */
    formatRate(rate) {
      const num = Number(rate)
      if (isNaN(num)) return '0.00'
      return num.toFixed(2)
    },

    /**
     * 计算行的总达标率（百分比，0-100）
     * - 优先使用后端提供的 `totalQualifiedRate`
     * - 若缺失，尝试使用 `totalQualifiedCount/totalOpenCount*100`
     * - 若仍缺失，按品牌数据 `brandData` 进行加权汇总（达标和/开业和*100）
     * @param {Object} row 一行数据对象
     * @returns {number} 总达标率（0-100 的数值）
     */
    getRowTotalQualifiedRate(row) {
      if (!row || typeof row !== 'object') return 0
      const r1 = Number(row.totalQualifiedRate)
      if (!isNaN(r1)) return r1

      const openTotal = Number(row.totalOpenCount)
      const qualifiedTotal = Number(row.totalQualifiedCount)
      if (!isNaN(openTotal) && !isNaN(qualifiedTotal) && openTotal > 0) {
        return (qualifiedTotal / openTotal) * 100
      }

      // 品牌数据加权汇总
      let openSum = 0
      let qualifiedSum = 0
      if (Array.isArray(row.brandData)) {
        row.brandData.forEach(c => {
          openSum += Number(c && c.openCount) || 0
          qualifiedSum += Number(c && c.qualifiedCount) || 0
        })
      }
      if (openSum > 0) return (qualifiedSum / openSum) * 100
      return 0
    },

    /**
     * 根据品牌编码获取中文名称
     * - 来源：品牌字典 `brandOptions`（字段：`enCode`、`fullName`）
     * - 回退：未匹配时返回原编码
     * @param {string} brandCode 品牌编码
     * @returns {string} 中文品牌名
     */
    getBrandName(brandCode) {
      const item = Array.isArray(this.brandOptions) ? this.brandOptions.find(b => b.enCode === brandCode) : null
      return item && item.fullName ? item.fullName : brandCode
    },

    /**
     * 表格汇总行计算
     * - 汇总列：总开业/总达标/总达标率
     * - 品牌列：分别对开业数与达标数求和，达标率按加权（达标和/开业和）计算
     */
    getTableSummaries({ columns, data }) {
      const sums = []
      columns.forEach((col, index) => {
        if (index === 0) {
          sums[index] = ''
          return
        }

        // 品牌动态列或汇总列
        const label = col.label
        if (label === '辅导师') {
          sums[index] = ''
          return
        }
        if (label === '汇总') {
          const totalOpen = data.reduce((acc, row) => acc + Number(row.totalOpenCount || 0), 0)
          const totalQualified = data.reduce((acc, row) => acc + Number(row.totalQualifiedCount || 0), 0)
          const rate = totalOpen === 0 ? 0 : (totalQualified / totalOpen) * 100
          const totalPass = data.reduce((acc, row) => acc + Number(row.totalPassCount || 0), 0)
          const passRate = totalOpen === 0 ? 0 : (totalPass / totalOpen) * 100
          sums[index] = `开业：${totalOpen}｜达标：${totalQualified}｜及格：${totalPass}\n达标率：${this.formatRate(rate)}%｜及格率：${this.formatRate(passRate)}%`
          return
        }

        // 对应品牌列的加权汇总（以 columnKey 作为品牌编码）
        const brand = col.columnKey || label
        let openSum = 0
        let qualifiedSum = 0
        let passSum = 0
        data.forEach(row => {
          openSum += Number(this.getBrandMetric(row, brand, 'openCount'))
          qualifiedSum += Number(this.getBrandMetric(row, brand, 'qualifiedCount'))
          passSum += Number(this.getBrandMetric(row, brand, 'passCount'))
        })
        const rate = openSum === 0 ? 0 : (qualifiedSum / openSum) * 100
        const passRate = openSum === 0 ? 0 : (passSum / openSum) * 100
        sums[index] = `开业：${openSum}｜达标：${qualifiedSum}｜及格：${passSum}\n达标率：${this.formatRate(rate)}%｜及格率：${this.formatRate(passRate)}%`
      })
      return sums
    }
  }
}
</script>

<style scoped>
@import './shared-table-styles.scss';

.cell-3 {
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.metric {
  display: inline-block;
  line-height: 20px;
}
.metric-line {
  display: flex;
  align-items: center;
  gap: 6px;
}
.metric-line .num {
  font-weight: 600;
}
.metric-line .sep {
  color: #909399;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.header-left span {
  margin-left: 6px;
  font-weight: 500;
}
.table-container {
  margin-top: 10px;
  overflow-x: auto;
}
.report-table :deep(.el-table__footer-wrapper) .cell {
  white-space: pre-wrap;
}
.report-table :deep(.el-table__body-wrapper) .cell {
  white-space: nowrap;
}
.report-table :deep(.el-table__header-wrapper) .cell {
  white-space: nowrap;
}
.report-table {
  min-width: 1200px;
}
</style>
